<template>
  <div class="up-controls">
    <div>
      <label for="kafka-broker">broker</label>
      <input id="kafka-broker" v-model="kafkaBrokers">
      <button :disabled='connectKafkaSuccess' @click="connectKafka">连接</button>
      <label for="interval-second">发送间隔(ms)</label>
      <input id="interval-second" type="number" v-model="intervalSecond" @change="onIntervalChange">
      <button :disabled='!connectKafkaSuccess' @click="onStartStopSend">{{ sendStatus ? '停止发送' : '开始发送' }}</button>
    </div>
    <div>
      <label>发送:</label>
      <label class="num">{{ sendCount }}</label>
      <label class="send-success">成功:</label>
      <label class="num send-success">{{ successCount }}</label>
      <label class="send-fail">失败:</label>
      <label class="num send-fail">{{ failCount }}</label>
    </div>
  </div>
</template>

<script>
import {ipcRenderer} from 'electron'

export default {
  name: 'KafkaConnect',
  data () {
    return {
      intervalSecond: 1000, // 发送间隔时间(毫秒)
      kafkaBrokers: '192.168.180.38:6667',
      sendStatus: false, // 发送开关(默认关)
      timer: null,
      successCount: 0, // 发送成功条数
      failCount: 0, // 发送失败条数
      connectKafkaSuccess: false
    }
  },
  props: {
    sendCount: { // 总发送数量,这个需要由父组件传进来,因为本组件不处理发送事件
      type: [Number],
      required: true
    }
  },
  methods: {
    /**
     * 点'开始发送'/'停止发送'按钮
     */
    onStartStopSend () {
      this.sendStatus = !this.sendStatus
      if (this.sendStatus) { // 要开启
        this.sendAll() // 立即执行一次
        this.timer = setInterval(this.sendAll, this.intervalSecond)
      } else { // 要关闭
        clearInterval(this.timer)
        this.timer = null
      }
    },
    /**
     * 发送消息方法(只是向父组件发送事件)
     */
    sendAll () {
      this.$emit('onSend')
    },
    onIntervalChange () {
      if (this.intervalSecond < 1) this.intervalSecond = 1
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = setInterval(this.sendAll, this.intervalSecond)
      }
    },
    connectKafka () {
      ipcRenderer.invoke("connectKafkaChannel", this.kafkaBrokers).then(res => {
        console.log('渲染线程发送成功')
      });
    }
  },
  created () {
    // 渲染进程接收主进程的消息
    ipcRenderer.on('successChannel', (event, data) => {
      this.successCount++
    })
    ipcRenderer.on('failChannel', (event, data) => {
      this.failCount++
    })
    ipcRenderer.on('connectKafkaSuccessChannel', (event, data) => {
      this.connectKafkaSuccess = true
    })
  }
}
</script>

<style scoped>
.up-controls {
  display: flex;
  justify-content: space-between;
  padding-bottom: 5px;
}

#kafka-broker {
  width: 130px;
}

#interval-second {
  width: 40px;
}

.num {
  display: inline-block;
  min-width: 30px;
}

.send-success {
  color: #006400;
}

.send-fail {
  color: #8b0000;
}
</style>
